<template>
	<view class="uploadBox">
		<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :name="name" multiple
			:maxCount="maxCount" :width="width" :height="height">
			<slot name="image">
				<view class="imageBox">
					<u-icon name="camera" color="#909399" size="30"></u-icon>
				</view>
			</slot>
		</u-upload>
		<view class="title" v-if="title">{{title}}</view>
	</view>
</template>

<script>
	import {
		HTTP_IMG_URL
	} from '@/config/app.js'
	import store from '@/store';
	export default {
		name: "upload-image",
		data() {
			return {
				fileList: []
			};
		},
		props: {
			name: {
				type: String,
				default: 'fileList' //上传组件的名称
			},
			maxCount: {
				type: Number,
				default: 10 //最大上传数量
			},
			width: {
				type: String,
				default: '160rpx' //上传组件的宽度
			},
			height: {
				type: String,
				default: '160rpx' //上传组件的高度
			},
			title: {
				type: String,
				default: null //文件上传提示词
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.uploadSuccess(event)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.$uploadFilePromise(lists[i].url)
					console.log(result, 999)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.fullurl,
						img: result.url
					}))
					fileListLen++
				}
				this.uploadSuccess(event)
			},
			uploadSuccess(event) {
				let fileList = this.fileList.map(item => {
					return item.img
				})
				this.$emit('uploadSuccess', {
					name: event.name,
					fileList: fileList.join(',')
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.uploadBox {
		.title {
			font-size: 28rpx;
			text-align: center;
			margin-top: 14rpx;
		}
	}

	.imageBox {
		background-color: #F4F5F7;
		width: 160rpx;
		height: 160rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 10rpx;
	}
</style>